package com.xian.tszs.meal.api;

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.xian.tszs.meal.annotation.UserLoginToken;
import com.xian.tszs.meal.component.WeChatComponent;
import com.xian.tszs.meal.entity.TsUser;
import com.xian.tszs.meal.service.TsUserManageService;
import com.xian.tszs.meal.utils.TokenUtil;

@Controller
@RequestMapping("wechat")
public class WeChatLoginController {

	@Autowired
	private WeChatComponent weChatComponent;

	@Autowired
	private TsUserManageService tsUserManage;

	/***
	 * 接受前台发送的Code 返回登录态 就是Token
	 * 
	 * @author: MRC
	 * @date 2019年5月22日 下午2:48:11
	 * @return String 返回类型
	 */
	@GetMapping("login")
	@ResponseBody
	private Map<String, Object> login(String code) {
		Map<String, String> map = weChatComponent.getWechatLoginStatus(code);
		Map<String, Object> mapp = new HashMap<String, Object>();
		String openId = map.get("openid");
		
		mapp.put("success", false);
		if (StringUtils.isEmpty(openId)) {
			mapp.put("msg", "错误！");
			return mapp;
		}
		String token = tsUserManage.sendToken(openId);
		
		mapp.put("token", token);
		mapp.put("success", true);
		return mapp;
	}
	
	/***
	 * 修改用户基本信息
	* @author: MRC  
	* @date 2019年5月22日 下午3:35:08 
	* @return Map<String,Object> 返回类型
	 */
	@PostMapping("updateUserInfo")
	@ResponseBody
	@UserLoginToken
	private Map<String, Object> updateUserInfo(@RequestBody TsUser tsUser) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		String id = TokenUtil.getTokenUserId();
		tsUser.setId(id);
		
		tsUserManage.updateUserInfo(tsUser);
		
		return map;
	}
	/***
	 * 绑定手机号
	* @author: MRC  
	* @date 2019年5月22日 下午4:10:05 
	* @return Map<String,Object> 返回类型
	 */
	@PostMapping("updateUserPhone")
	@ResponseBody
	@UserLoginToken
	private Map<String, Object> updateUserPhone(String phone) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		String id = TokenUtil.getTokenUserId();
		
		map.put("success", false);
		if (StringUtils.isEmpty(phone)) {
			map.put("msg", "参数缺失！");
			return map;
		} else {
			tsUserManage.updateUserPhone(phone,id);
			map.put("success", true);
			map.put("msg", "修改成功！");
		}
		return map;
	}
}
